import { useNavigate } from "react-router-dom";

import { appConfig } from "~/modules/shared/app-config";
import { isUrl } from "~/modules/shared/utils/url";

export const useSafeRouter = () => {
  const appConfigStore = appConfig;
  const router = useNavigate();
  const goto = async (path?: string): Promise<void> => {
    if (!path) {
      return Promise.resolve();
    }
    path = decodeURIComponent(path);
    if (isUrl(path)) {
      window.location.href = path;
      return Promise.resolve();
    }
    const basePath =
      appConfigStore.contextPath === "/" ? "" : appConfigStore.contextPath;
    await router(`${basePath}${path}`);
  };

  const goBack = async (path?: string): Promise<void> => {
    if (path) {
      return await goto(path);
    } else {
      window.history.back();
      return Promise.reject();
    }
  };

  return {
    goto,
    goBack,
    router,
  };
};
